$(function ready() {
    // 动态获取仓库列表
    writeRepositorySelect($("#searchRepository"))
    /**
     * 列表数据
     */
    $("#productTable").bootstrapTable({
        url: "/product/list",
        method: "get",
        pagination: true,   //是否显示分页（*）
        pageSize: 10,       //每页的记录行数（*）
        pageList: [10, 20, 50, 100, 'All'], //可供选择的每页的行数（*）
        sidePagination: "client",    //分页方式：client客户端分页，server服务端分页（*）
        pageNumber: 1,                    //初始化加载第一页，默认第一页
        classes: "table table-bordered table-striped table-condensed table-hover",
        queryParams: function (params) {
            return getParams(params);
        },
        // 动态修改行的背景颜色
        rowStyle: function (row, index) { //row：行对象， index ：第几行
            return getRowStyle(row, index);
        },
        onDblClickCell: function (field, value, row, $element) {
            return onDblClickCell(field, value, row, $element);
        },
        columns: [{
            title: "商品id",
            field: "id",
            visible: false
        }, {
            title: "商品名称",
            field: "name",
        }, {
            title: "类型",
            field: "type",
            formatter: function (value, row, index) {
                if (value == 0) {
                    return "常规商品";
                } else {
                    return "不发货商品";
                }
            }
        }, {
            title: "库存数量（盒/箱）",
            field: "boxNum",
        }, {
            title: "前30天销量（盒）",
            field: "warnBoxNum",
        }, {
            title: "入库成本：元",
            field: "costYuan",
        }, {
            title: "商品简称",
            field: "simpleName",
        }, {
            title: "散装库存",
            field: "num",
        }, {
            title: "规格（个/盒）",
            field: "perBox",
        }, {
            title: "备注",
            field: "note",
        }, {
            title: "重量：g",
            field: "weightGram",
        }, {
            title: "仓库名称",
            field: "repositoryName",
        }, {
            field: 'operate',
            title: '操作',
            align: 'center',
            valign: 'middle',
            width: 200,
            events: {
                'click #update': function (e, value, row, index) {
                    updateOne(e, value, row, index);
                },
                'click #delete': function (e, value, row, index) {
                    deleteOne(e, value, row, index);
                }
            },
            formatter: function (value, row, index) {
                let result = "";
                result += '<button id="update" class="btn btn-info" data-toggle="modal" data-target="#updateModal">保存修改</button>';
                let deleteStr = !row.isDelete ? '删除' : '恢复';
                result += '<button id="delete" class="btn btn-danger" data-toggle="modal" data-target="#deleteModal" style="margin-left:10px;">' + deleteStr + '</button>';
                return result;
            }

        }]
    });

    /**
     * 设置样式
     */
    function getRowStyle(row, index) {
        if (row.isDelete != 0) {
            return {css: {"background-color": 'Gray'}};
        } else if (row.boxNum < 0) {
            //库存小于0，即已经缺货
            return {css: {"background-color": 'OrangeRed'}};
        } else if (row.boxNum < row.warnBoxNum) {
            //预警库存不为0，且库存低于预警库存
            return {css: {"background-color": 'Yellow'}};
        } else {
            return {css: {"background-color": 'White'}};
        }
    }


    /**
     * 这里可以自定义处理查询参数，包括添加默认参数
     * @param params
     * @returns {*}
     */
    function getParams(params) {
        params = $.extend({}, params, {
            name: $("#searchName").val(),
            repositoryId: $("#searchRepository").val(),
            note: $("#searchNote").val(),
            type: $("#searchType").val(),
            isDelete: $("#searchIsDelete").val()
        });
        return params;
    }

});


/**
 * 根据输入的商品名称
 * 查询并更新商品下拉框的选项
 * @param $name 检测输入改变的输入框，一般是name，同时需要填充id
 * @param $ul
 * @param name $name
 */
function writeProductUl($id, $name, $ul) {
    $.get({
        url: "/product/list",
        dataType: "json",
        data: {
            name: $name.val(),
            isDelete: 0,
            repositoryId: -1,
        },
        success: function (result) {
            writeUlOnChange($id, $name, $ul, result.data);
        }, error: function (xhr, status, error) {
            console.error("Error: " + status + ", " + error);
        }
    });

}


/**
 * 按下Enter查询
 */
$(document).keyup(function (event) {
    if (event.keyCode == 13) {
        search();
    }
});

/**
 * 根据输入的条件重新查询
 */
function search() {
    $("#productTable").bootstrapTable('refresh');
}

/**
 * 查询按钮点击事件
 */
$("#search").click(search);

/**
 * 重置按钮
 */
$("#reset").click(function () {
    $("#searchName").val("");

    $("#searchRepository").val("-1");
    $("#searchRepository").selectpicker("refresh");

    $("#searchNote").val("");

    $("#searchIsDelete").val("0");
    $("#searchIsDelete").selectpicker("refresh");

    $("#searchType").val("");
    $("#searchType").selectpicker("refresh");

})
/**
 * 列表导出
 */
$("#export").click(function () {
    $.get({
        url: '/product/export',
        contentType: 'application/json; charset=utf-8',
        data: {
            name: $("#searchName").val(),
            repositoryId: $("#searchRepository").val(),
            note: $("#searchNote").val(),
            type: $("#searchType").val(),
            isDelete: $("#searchIsDelete").val()
        },
        dataType: 'json',
        success: function (result) {
            layerShow(result);
        }
    });
});

/**
 * 新增按钮
 */
$("#addOne").click(function () {
    $.post({
        url: '/product/addOne',
        async: false,//同步，默认是true，异步
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            name: $("#addName").val(),
            simpleName: $("#addSimpleName").val(),
            type: $("#addType").val(),
            costYuan: $("#addCostYuan").val(),
            weightGram: $("#addWeightGram").val(),
            perBox: $("#addPerBox").val(),
            note: $("#addNote").val()
        }),
        dataType: 'json',
        success: function (result) {
            layerShow(result);
            search();
        }
    });
    $("#addModal").modal('hide');
})

/**
 * 表格内元素的点击事件
 * @param fieldName
 * @param value
 * @param row
 * @param element
 */
function onDblClickCell(fieldName, value, row, $element) {
    // 不处理的字段
    if (fieldName == 'warnBoxNum' || fieldName == 'repositoryName') {
        return;
    }
    textToInput($("#productTable"), fieldName, row, $element);
}

/**
 * bootstrap中，修改某个字段时，
 * 同步中修改相关的字段，同时修改bootstrap中的row
 * @type {{syncData: Window.productTable.syncData}}
 */
window.productTable = {
    syncData: function ($table, fieldName, row, $td) {
        // 当前行所有td
        let $tds = $td.parent().children();

        let $num = $($tds[getTdIndexByFiled($table, "num")]);
        let $boxNum = $($tds[getTdIndexByFiled($table, "boxNum")]);
        console.log(getTdIndexByFiled($table, "num"));
        console.log(getTdIndexByFiled($table, "boxNum"));
        switch (fieldName) {
            case 'boxNum':
                // boxNum -> num
                row["num"] = (row["boxNum"] * row["perBox"]).toFixed(0);
                $num.html("<span>" + row["num"] + "</span>");
                $num.css("color", "red");
                break;
            case 'num':
                // num -> boxNum
                row["boxNum"] = (row["num"] / row["perBox"]).toFixed(2);
                $boxNum.html("<span>" + row["boxNum"] + "</span>");
                $boxNum.css("color", "red");
                break;
            case 'perBox':
                // perBox -> boxNum
                row["boxNum"] = (row["num"] / row["perBox"]).toFixed(2);
                $boxNum.html("<span>" + row["boxNum"] + "</span>");
                $boxNum.css("color", "red");
                break;
        }
    }
}

/**
 * 修改当前行数据
 * @param e
 * @param value
 * @param row
 * @param index
 */
function updateOne(e, value, row, index) {
    $.post({
        url: '/product/updateOne',
        async: false,//同步，默认是true，异步
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(row), // 将对象转换为JSON字符串
        dataType: 'json',
        success: function (result) {
            layerShow(result);
            search();
        }
    });
}

/**
 * 删除或恢复 当前行
 * @param e
 * @param value
 * @param row
 * @param index
 */
function deleteOne(e, value, row, index) {
    $.post({
        url: '/product/deleteOne',
        async: false,//同步，默认是true，异步
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            id: row.id,
            isDelete: row.isDelete == 0 ? 1 : 0
        }),
        dataType: 'json',
        success: function (result) {
            layerShow(result);
            search();
        }
    });
}


